<template>
  <!-- 模板部分保持不变 -->
  <a-form :model="formData" layout="vertical">
    <a-form-item label="抄送人员">
      <a-select
        v-model:value="formData.userIds"
        mode="multiple"
        show-search
        :filter-option="filterOption"
        :options="users"
        allowClear
        placeholder="请选择抄送人员"
        style="width: 100%"
      />
    </a-form-item>

    <a-form-item label="抄送角色">
      <a-select
        v-model:value="formData.roleIds"
        mode="multiple"
        show-search
        :filter-option="filterOption"
        :options="roles"
        allowClear
        placeholder="请选择抄送角色"
        style="width: 100%"
      />
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import { reactive, watch, inject, onMounted } from "vue";
import { message } from "ant-design-vue";
import userFilterOption from "@/hooks/userFilterOption";

const { filterOption } = userFilterOption();

// 注入依赖项
const updateProperties: any = inject("updateProperties");
const _bpmnElement: any = inject("bpmnElement");
const _bpmnInstances: any = inject("bpmnInstances");

const props = defineProps({
  bpmnElementId: {
    type: String,
  },
  users: {
    type: Array,
    required: true,
  },
  roles: {
    type: Array,
    required: true,
  },
  groups: {
    type: Array,
    required: true,
  },
  categorys: {
    type: Array,
    required: true,
  },
  businessObject: Object,
  type: {
    type: String,
    default: "",
  },
});

const formData = reactive({
  userIds: [] as string[],
  roleIds: [] as string[],
});

// 初始化表单数据（保持不变）
const initFormData = () => {
  const bpmnElement = _bpmnElement();
  const businessObject = bpmnElement.businessObject;

  formData.userIds = [];
  formData.roleIds = [];

  const extensionElements = businessObject.get("extensionElements");
  if (extensionElements) {
    const inputOutput = extensionElements.values.find(
      (element: any) => element.$type === "camunda:InputOutput"
    );

    if (inputOutput) {
      const userIdParam = inputOutput.inputParameters.find(
        (param: any) => param.name === "ccUserId"
      );
      if (userIdParam && userIdParam.list) {
        // formData.userIds = userIdParam.list.values.map((v: any) => v.text);
        formData.userIds = userIdParam.list.values
          .map((v: any) => (v.value !== undefined ? Number(v.value) : ""))
          .filter(Boolean);
      }

      const roleIdParam = inputOutput.inputParameters.find(
        (param: any) => param.name === "ccRoleId"
      );
      if (roleIdParam && roleIdParam.list) {
        // formData.roleIds = roleIdParam.list.values.map((v: any) => v.text);
        formData.roleIds = roleIdParam.list.values
          .map((v: any) => (v.value !== undefined ? Number(v.value) : ""))
          .filter(Boolean);
      }
    }
  }
};

// 更新BPMN元素（关键修改部分）
const updateBpmnElement = () => {
  const bpmnInstances = _bpmnInstances();
  const modeling = bpmnInstances.modeling;
  const bpmnFactory = bpmnInstances.bpmnFactory;
  const element = _bpmnElement();

  // 创建inputOutput扩展元素
  const inputOutput = bpmnFactory.create("camunda:InputOutput");
  inputOutput.$parent = element.businessObject; // 设置父元素

  // 创建用户ID输入参数
  if (formData.userIds.length > 0) {
    const userIdList = bpmnFactory.create("camunda:List");
    userIdList.$parent = inputOutput; // 设置父元素

    // 创建value元素数组
    userIdList.values = formData.userIds.map((userId) => {
      const value = bpmnFactory.create("camunda:Value", {
        value: String(userId), // 确保转换为字符串
      });
      value.$parent = userIdList;
      return value;
    });

    const userIdParam = bpmnFactory.create("camunda:InputParameter", {
      name: "ccUserId",
    });
    userIdParam.$parent = inputOutput; // 设置父元素
    userIdParam.list = userIdList; // 关联list

    inputOutput.inputParameters = [userIdParam];
  }

  // 创建角色ID输入参数
  if (formData.roleIds.length > 0) {
    const roleIdList = bpmnFactory.create("camunda:List");
    roleIdList.$parent = inputOutput; // 设置父元素

    // 创建value元素数组
    roleIdList.values = formData.roleIds.map((roleId) => {
      const value = bpmnFactory.create("camunda:Value", {
        value: String(roleId), // 确保转换为字符串
      });
      value.$parent = roleIdList;
      return value;
    });

    const roleIdParam = bpmnFactory.create("camunda:InputParameter", {
      name: "ccRoleId",
    });
    roleIdParam.$parent = inputOutput; // 设置父元素
    roleIdParam.list = roleIdList; // 关联list

    // 如果已经有用户参数，则追加角色参数
    if (inputOutput.inputParameters) {
      inputOutput.inputParameters.push(roleIdParam);
    } else {
      inputOutput.inputParameters = [roleIdParam];
    }
  }

  // 获取或创建extensionElements
  let extensionElements = element.businessObject.get("extensionElements");
  if (!extensionElements) {
    extensionElements = bpmnFactory.create("bpmn:ExtensionElements");
    extensionElements.$parent = element.businessObject; // 设置父元素
  }

  // 更新或添加inputOutput
  const existingInputOutputIndex = extensionElements.values?.findIndex(
    (el: any) => el.$type === "camunda:InputOutput"
  );

  if (
    existingInputOutputIndex !== undefined &&
    existingInputOutputIndex !== -1
  ) {
    if (inputOutput.inputParameters && inputOutput.inputParameters.length > 0) {
      extensionElements.values[existingInputOutputIndex] = inputOutput;
    } else {
      // 如果没有参数，则移除inputOutput
      extensionElements.values.splice(existingInputOutputIndex, 1);
    }
  } else if (
    inputOutput.inputParameters &&
    inputOutput.inputParameters.length > 0
  ) {
    if (!extensionElements.values) {
      extensionElements.values = [];
    }
    extensionElements.values.push(inputOutput);
  }

  // 如果extensionElements有值则更新，否则移除
  if (extensionElements.values && extensionElements.values.length > 0) {
    modeling.updateProperties(element, {
      extensionElements,
    });
  } else {
    modeling.updateProperties(element, {
      extensionElements: undefined,
    });
  }
};

// 监听表单变化和初始化（保持不变）
watch(
  () => formData,
  () => {
    updateBpmnElement();
  },
  { deep: true }
);

watch(
  () => props.businessObject,
  () => {
    initFormData();
  },
  { immediate: true }
);

onMounted(() => {
  initFormData();
});
</script>
